package service;
import java.util.List;

import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import common.kit.AppMsgKit;
import common.kit.PageSql;
import enums.CompanyStatus;
import model.Company;
import model.ServicerCompany;
import model.Station;
import model.Unbind;
import model.Wxuser;

public class ServicerCompanyService extends BaseService {

	public Ret save(Company company , Wxuser wxuser) {
		new CompanyService().save(company) ;
		ServicerCompany servicerCompany = ServicerCompany.dao.findFirstByServiserIdAndCompanyId(wxuser.getCompanyId(), company.getId());
		if (null != servicerCompany) {
			return ok() ;
		}
		servicerCompany = new ServicerCompany();
		servicerCompany.setCompanyId(company.getId());
		servicerCompany.setServiserId(wxuser.getCompanyId());
		servicerCompany.save() ;
		//下发通知
		AppMsgKit.sendBindMsg();
		return ok();
    }

	public Page<Record> getApiPage(Kv kv , Integer pageNumber , Integer pageSize) {
		kv.set("tc.isDelete",0);
		String select = " tsc.id,tsc.companyId,tc.name,tc.address,tc.latitude,tc.longitude,tc.contacts,tc.mobile,tc.industry,tc.status " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_servicer_company tsc ") ;
	    pageSql.join(" t_servicer ts " , " ts.id = tsc.serviserId ") ;
	    pageSql.join(" t_company tc " , " tc.id = tsc.companyId ") ;
		pageSql.setEqualCondition("tsc.serviserId") ;
		pageSql.setEqualCondition("tc.isDelete") ;
		pageSql.setLikeCondition("tc.name") ;
	    pageSql.orderBy(" tc.name ASC ");
		Page<Record> page = pageSql.paginate( pageNumber , pageSize) ;
		List<Record> list = page.getList();
		for (Record record : list) {
			record.set("statusStr", CompanyStatus.getTitleByValue(record,"status"))	;
		}
		return page ;
	}
	
	public Ret remove(Long id , int status ) {
		Unbind unbind = Unbind.dao.findById(id);
		if (null == unbind) {
			return fail() ;
		}
		if (!unbind.isAuditingStatus()) {
			return fail("状态已变更");
		}
		unbind.setStatus(status);
		unbind.update();
		if (unbind.isRefusedStatus()) {
			return ok() ;
		}
		ServicerCompany servicerCompany = new ServicerCompany();
		servicerCompany.setId(unbind.getScId());
		servicerCompany.delete();
		Long servicerId = unbind.getServicerId();
		Station.dao.removeByServicerId(servicerId);
		return ok() ;
	}
	
	public Ret unbind(ServicerCompany servicerCompany) {
		Unbind unbind = Unbind.dao.findFirstByScId(servicerCompany.getId());
		if (null != unbind && unbind.isAuditingStatus()) {
			return fail("解绑申请审核中");
		}
		unbind = new Unbind();
		unbind.setScId(servicerCompany.getId());
		unbind.setServicerId(servicerCompany.getServiserId());
		unbind.setCompanyId(servicerCompany.getCompanyId());
		unbind.save();
		return ok() ;
	}
}
